package OrgenizeResults;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.security.AllPermission;
import java.util.ArrayList;

public class ResultsGetter {

	/**
	 * @param args
	 */
	ArrayList<ArrayList<Integer>>data_arr;
	
	public ResultsGetter(){
		data_arr=new ArrayList<ArrayList<Integer>>();
		for(int i=0;i<5000;i++){
			ArrayList<Integer>oneList=new ArrayList<Integer>();
			data_arr.add(oneList);
		}
	}
	public void insert(int location,int value){
		ArrayList<Integer>tmp=data_arr.remove(location);
		tmp.add(value);
		data_arr.add(location, tmp);
	}
	public String getLine(int idx){
		StringBuilder sb=new StringBuilder();
		sb.append(data_arr.get(idx).get(0));
		for(int i=1;i<data_arr.get(idx).size();i++){
			sb.append(",");
			sb.append(data_arr.get(idx).get(i));
		}
		return sb.toString();
	}
	public int getId(String path) throws Exception{
		BufferedReader inFile = new BufferedReader (new FileReader (path));
		String line=inFile.readLine();
		while(line!=null){
			if(line.startsWith("RESULT")){
				String[] res=line.split(",");
				inFile.close();
				return (Integer.parseInt(res[1]));
			}
			line=inFile.readLine();
		}
		inFile.close();
		return -1;
	}
	public static void main(String[] args) throws Exception {
		ResultsGetter rg=new ResultsGetter();
		ArrayList<String> directories=new ArrayList<String>();
		BufferedReader inFile = new BufferedReader (new FileReader ("agents.txt"));
        String line=inFile.readLine();
        while(line !=null){
        	directories.add(line);
        	line=inFile.readLine();
        }
		String path="/home/sarne/part2/logs/";
		for(int i=0;i<directories.size();i++){
			String directory=directories.get(i);
			for(int j=1;j<=5000;j++){
				rg.insert(j-1, rg.getId(path+directory+"/"+j+".srv.log"));
			}
		}
		//print to file
		FileWriter fstream = new FileWriter("allResults.csv",true);
		BufferedWriter out = new BufferedWriter(fstream);
		for(int i=0;i<5000;i++){
			String lineOut=rg.getLine(i);
			out.append(lineOut);
			out.append("\n");
		}
		out.close();
	}

}
